<template>
  <el-button-group>
    <el-button :type="btnType == 'info' ? 'primary' : 'default'" @click="onBtns('info')">个人信息</el-button>
    <el-button :type="btnType == 'setting' ? 'primary' : 'default'" @click="onBtns('setting')">账号设置</el-button>
  </el-button-group>
  <div v-if="btnType == 'info'" class="info">
    <el-form ref="refInfoForm" label-width="auto" :model="infoForm">
      <el-form-item label="姓名:">
        <el-input v-model="infoForm.username" placeholder="请填写您的姓名" />
      </el-form-item>
      <el-form-item label="所在城市:">
        <el-cascader v-model="currentCity" :props="{ value: 'code', label: 'value' }" :options="citys" clearable
          @change="cityHandler" placeholder="请选择省-市-区-县">
          <template #default="{ node, data }">
            <span>{{ data.value }}</span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="机构名称:">
        <!-- <el-cascader v-model="infoForm.companyName" :options="infoForm.companyNames" placeholder="请选择您的单位名称" /> -->
        <el-input v-model="infoForm.companyName" placeholder="请填写您的单位名称" />
      </el-form-item>
      <el-form-item label="个人职务:">
        <!-- <el-cascader v-model="infoForm.job" :options="infoForm.jobs" placeholder="请选择您的个人职务" /> -->
        <el-input v-model="infoForm.job" placeholder="请填写您的个人职务" />
      </el-form-item>
      <el-form-item label="联系电话:">
        <el-input v-model="infoForm.tel" placeholder="请填写你的联系电话" />
      </el-form-item>
      <el-form-item label="联系邮箱:">
        <el-input v-model="infoForm.email" placeholder="请填写您的联系邮箱" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitInfoForm(infoForm)">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div v-if="btnType == 'setting'" class="setting">
    <div class="setting-container">
      <div class="userinfo">
        <div class="user-title">
          <h3>用户信息</h3>
        </div>
        <div class="update-info">
          <el-form label-width="auto" label-position="right" ref="updateFormRef" style="max-width: 500px"
            :model="updateForm" class="update-form">
            <el-form-item label="用户账号：">
              <el-input v-model="updateForm.username" class="input" />
              <span @click="onUserNameClick" class="update-btn">修改</span>
            </el-form-item>
            <el-form-item label="用户头像：">
              <el-upload :action="postUrl" :show-file-list="false" class="avatar-uploader"
                :on-success="handleAvatarSuccess">
                <img v-if="updateForm.imageUrl" :src="updateForm.imageUrl" class="avatar" />
              </el-upload>
              <span @click="onAvatarClick" class="update-btn">修改</span>
            </el-form-item>
            <el-form-item label="手机号码：">
              <el-input v-model="updateForm.tel" class="input" />
              <span @click="onPhoneNumClick" class="update-btn">绑定</span>
            </el-form-item>
            <el-form-item label="密码：">
              <el-input type="password" v-model="updateForm.password" class="input" />
              <span @click="onPasswordClick" class="update-btn">修改密码</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="user-title">
          <h3>子账号管理</h3>
        </div>
      </div>
    </div>
    <el-button @click="addUserDialogVisible = true" class="account-btn" type="primary">新增子账号</el-button>
    <div class="account-container">
      <el-table :header-cell-style="{ background: '#f5f6fa', height: '55px', color: '#000000' }" stripe class="account"
        :data="childUserTableData">
        <el-table-column align="center" label="序号" width="80">
          <template #default="scope">
            <div>{{ scope.$index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="userName" label="用户名" width="250" />
        <el-table-column align="center" prop="password" label="密码">
          <template #default="scope">
            <div>******</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phonenumber" label="绑定手机号" />
        <el-table-column align="center" prop="status" label="是否启用">
          <template #default="scope">
            <SwitchView :status="scope.row.status" :userId="scope.row.userId" />
          </template>
        </el-table-column>
        <el-table-column class="handle" align="center" label="操作">
          <template #default="scope">
            <span @click="updateChildUserHandler(scope.row)">编辑</span>
            <span @click="delChildUserHandler(scope.row.userId)" style="margin-left: 40px;">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <!-- <el-pagination class="pagination" background layout="prev, pager, next" :total="1000" /> -->
    <!-- 增加子用户-弹出框 -->
    <el-dialog :lock-scroll="false" v-model="addUserDialogVisible" title="新增子账号" width="500" class="el-dialog">
      <el-form ref="formRef" style="max-width: 500px" :model="childUserForm" label-width="auto">
        <el-form-item label="账号">
          <el-input size="large" v-model="childUserForm.userName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input size="large" type="password" v-model="childUserForm.password" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input size="large" v-model="childUserForm.phonenumber" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input size="large" v-model="childUserForm.nickName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddUserHandler">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改子用户-弹出框 -->
    <el-dialog :lock-scroll="false" v-model="updateUserDialogVisible" title="修改子账号" width="500" class="el-dialog">
      <el-form ref="formRef" style="max-width: 500px" :model="updateChildUserForm" label-width="auto">
        <el-form-item label="账号">
          <el-input size="large" v-model="updateChildUserForm.userName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input size="large" type="password" v-model="updateChildUserForm.password" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input size="large" v-model="updateChildUserForm.phonenumber" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input size="large" v-model="updateChildUserForm.nickName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onUpdateUserHandler">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue"
import citys from '../../assets/json/citys.json'
import { getUserInfo, updateUserInfo, addUser, getChildUser, delChildUser, updateChildUser } from "../../api/user"
import useUserStore from "../../stores/modules/user"
import avatar from "../../assets/images/icon.png"
import { ElLoading, ElMessage } from 'element-plus'
import SwitchView from "./ChildView/SwitchView.vue"

const btnType = ref("info")
const userStore = useUserStore()
const currentCity = ref([])
const deptId = ref(0)
const addUserDialogVisible = ref(false)
const updateUserDialogVisible = ref(false)
const postUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/qiniu/image`)
const childUserTableData = ref([])

const infoForm = ref({
  username: "",
  companyName: '',
  job: '',
  tel: "",
  email: ""
})

const updateForm = ref({
  username: "",
  imageUrl: avatar,
  tel: "",
  password: "******"
})

const childUserForm = ref({
  userName: "",
  password: "",
  phonenumber: "",
  nickName: ""
})

const updateChildUserForm = ref({
  userId: "",
  userName: "",
  password: "",
  phonenumber: "",
  nickName: ""
})

onMounted(() => {
  getUserInfo({ userId: userStore.id }).then(res => {
    if (res.data) {
      if (res.data.currentCity) {
        currentCity.value = res.data.currentCity.split(",");
      }
      if (res.data.dept) {
        infoForm.value.companyName = res.data.dept.deptName
      }
      if (res.data.posts) {
        infoForm.value.job = res.data.posts[0].postName
      }
      // 个人信息
      infoForm.value.username = res.data.userName;
      infoForm.value.tel = res.data.phonenumber;
      infoForm.value.email = res.data.email;
      // 账号设置
      updateForm.value.username = res.data.userName;
      updateForm.value.tel = res.data.phonenumber;
      updateForm.value.imageUrl = res.data.avatar;
      if (res.data.dept) {
        // 设置deptId
        deptId.value = res.data.dept.deptId
      }
    }
  })
})

const onBtns = (value) => {
  btnType.value = value
}

/**
 * 保存按钮
 */
const submitInfoForm = (formEl) => {
  updateUserInfo({
    "userId": userStore.id,
    "userName": formEl.username,
    "phonenumber": formEl.tel,
    "currentCity": currentCity.value.toString(),
    "email": formEl.email,
    "deptName": formEl.companyName
  }).then(res => {
    ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
  })
}

const cityHandler = () => {
  console.log(currentCity.value);
}

const handleAvatarSuccess = (response, uploadFile) => {
  updateForm.value.imageUrl = response
}

const onAddUserHandler = () => {
  addUser({
    userName: childUserForm.value.userName,
    password: childUserForm.value.password,
    phonenumber: childUserForm.value.phonenumber,
    nickName: childUserForm.value.nickName,
    subUserFlag: "1",
    userId: userStore.id
  }).then(res => {
    if (res.code === 200) {
      addUserDialogVisible.value = false
      httpChild()
      ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
    }
  })
}

/**
 * 修改用户信息
 */

const onUserNameClick = () => {
  updateUserInfo({
    userId: userStore.id,
    userName: updateForm.value.username
  }).then(res => {
    ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
  })
}

const onAvatarClick = () => {
  console.log({
    userId: userStore.id,
    userName: updateForm.value.username,
    avatar: updateForm.value.imageUrl
  });
  updateUserInfo({
    userId: userStore.id,
    userName: updateForm.value.username,
    avatar: updateForm.value.imageUrl
  }).then(res => {
    ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
  })
}

const onPhoneNumClick = () => {
  updateUserInfo({
    userId: userStore.id,
    userName: updateForm.value.username,
    phonenumber: updateForm.value.tel
  }).then(res => {
    ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
  })
}

const onPasswordClick = () => {
  // updateUserInfo({
  //   userId: userStore.id,
  //   userName: updateForm.value.username,
  //   password: updateForm.value.password
  // }).then(res => {
  //   ElMessage({ message: res.msg, type: 'success', duration: 5 * 1000 })
  // })
}

/**
 * 子账号
 */
const httpChild = () => {
  getChildUser({ userId: userStore.id }).then(res => {
    childUserTableData.value = res.rows
  })
}
onMounted(() => {
  httpChild()
})

const delChildUserHandler = (id) => {
  ElMessageBox.confirm(
    '你确定要删除这个子用户么？',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 删除
      delChildUser({ userId: id }).then(res => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        httpChild()
      })
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: 'info',
        message: '已经取消删除',
      })
    })
}

const updateChildUserHandler = (info) => {
  updateUserDialogVisible.value = true
  updateChildUserForm.value.userId = info.userId
  updateChildUserForm.value.userName = info.userName
  updateChildUserForm.value.password = info.password
  updateChildUserForm.value.phonenumber = info.phonenumber
  updateChildUserForm.value.nickName = info.nickName
}

const onUpdateUserHandler = () => {
  updateChildUser(updateChildUserForm.value).then(res => {
    updateUserDialogVisible.value = false
    ElMessage({ type: 'success', message: res.msg })
    httpChild()
  })
}

</script>

<style lang="less" scoped>
.ucenter-container {
  background-color: #fff;
  padding: 20px 40px;

  :deep(.el-tabs__header) {
    width: 60%;

    .el-tabs__nav-wrap:after {
      height: 0;
    }
  }

  :deep(.el-tabs__content) {
    padding-top: 10px;
    border-top: 1px solid #f3f4f5;
  }

  :deep(.el-cascader) {
    width: 100%;
  }

  :deep(.el-form-item__content) {
    justify-content: center;
  }

  .info {
    width: 400px;
    margin: 100px auto;
    margin-top: 50px;
    height: calc(100vh - 360px);
  }
}

.setting-container {
  padding: 20px 0;

  .userinfo {
    .user-title {
      border-bottom: 1px solid #f3f4f5;
      padding: 10px;

      h3 {
        position: relative;
        font-weight: 400;
        font-size: 18px;
        color: #2E2E2E;
        padding-left: 15px;
      }

      h3:before {
        content: "";
        background-color: #006EFF;
        width: 3px;
        height: 15px;
        position: absolute;
        left: 0;
        top: 5px;
        border-radius: 3px;
      }
    }

    .update-info {
      padding: 25px;

      .update-form {
        .input {
          flex: 1;
        }

        .update-btn {
          margin-left: 10px;
          width: 100px;
          color: #006EFF;
          cursor: pointer;
        }

        :deep(.el-form-item__content) {
          justify-content: start;
        }

        .avatar-uploader {
          :deep(.el-upload) {
            align-items: end;
          }

          img {
            width: 100px;
            border-radius: 50%;
          }
        }
      }
    }
  }
}

.account-btn {
  margin: 20px;
  margin-top: 0;
}

.account-container {
  padding: 10px;
  box-sizing: border-box;

  .account {
    width: 98%;
    box-shadow: 0 0 15px rgba(100, 100, 100, .2);
  }

}


.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  width: 80%;
  height: 80px;
  line-height: 80px;
  margin: 0 auto;
}
</style>